package com.atguigu.flink.chapter2;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2020/12/18 10:34
 */
public class Flink01_WC_Batch {
    public static void main(String[] args) throws Exception {
        // 1. 获取批次处理的执行环境
        ExecutionEnvironment benv = ExecutionEnvironment.getExecutionEnvironment();
        // 2. 读取数据
        DataSource<String> source = benv.readTextFile("input/words.txt");
        // 3. 各种转换处理
        FlatMapOperator<String, String> wordsFLO = source.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] split = value.split(" ");
                for (String word : split) {
                    out.collect(word);
                }
            }
        });

        MapOperator<String, Tuple2<String, Long>> wordAndOne = wordsFLO.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String value) throws Exception {
                return Tuple2.of(value, 1L);
            }
        });

        UnsortedGrouping<Tuple2<String, Long>> wordOneGrouped = wordAndOne.groupBy(0);

        AggregateOperator<Tuple2<String, Long>> result = wordOneGrouped.sum(1);
        // 4. 控制台输出
        result.print();

    }
}
